﻿using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using UnityEngine;

public class GameStateComponent : MonoBehaviour {

    public int currentLevel;

    public Dictionary<int, int> civiliansSaved = new Dictionary<int, int>();
    
    public void Awake()
    {
        DontDestroyOnLoad(gameObject);

        // Load from file
        Debug.Log("Loading from: " + Application.persistentDataPath + "/save.dat");
        if (File.Exists(Application.persistentDataPath + "/save.dat"))
        {
            BinaryFormatter bf = new BinaryFormatter();
            FileStream file = File.Open(Application.persistentDataPath + "/save.dat", FileMode.Open);
            civiliansSaved = (Dictionary<int, int>) bf.Deserialize(file);
            file.Close();
        }
    }

    public void SetCiviliansSaved(int level, int score)
    {
        civiliansSaved.Add(level, score);
        
        // save to file
        BinaryFormatter bf = new BinaryFormatter();
        FileStream file = File.Create(Application.persistentDataPath + "/save.dat");
        bf.Serialize(file, civiliansSaved);
        file.Close();
    }

    public int GetCiviliansSaved(int level)
    {
        return civiliansSaved.ContainsKey(level) ? civiliansSaved[level] : 0;
    }

    public int GetTotalCiviliansSaved()
    {
        int total = 0;
        foreach (int score in civiliansSaved.Values)
        {
            total += score;
        }
        return total;
    }

}
